package com.peisong.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.peisong.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

/***
 * 生成验证码图片的工具类
 * **/
public class VerifyCodeUtils {
    public Result getCode(RedisTemplate redisTemplate) {
        Map<String, String> result = new HashMap<>();
        Result Result = null;
        try {
            // 生成验证码图片
            BufferedImage image = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            Random r = new Random();
            //设置背景颜色
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            //填充区域
            g.fillRect(0, 0, 100, 30);
            //设置字体
            g.setColor(new Color(0, 0, 0));
            //设置字体大小
            g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
            String captcha="";
            //生成机数包含字母
            String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < 4; i++) {
                int index = random.nextInt(characters.length());
                builder.append(characters.charAt(index));
            }
            captcha = builder.toString();
            System.out.println("随机数： " + captcha);
            // 将验证码绘制到图片上
            g.drawString(captcha, 10, 20);
            // 将图片转换为base64格式
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            byte[] bytes = baos.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(bytes);
            // 将验证码存储到Redis中，并返回对应的key
            String key = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(key, captcha, 5, TimeUnit.MINUTES);
            result.put("key", key);
            result.put("base64", "data:image/png;base64,"+base64Image);

            Result = Result.success(result);
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        Result = Result.error("[]");
        return Result;
    }

    /**
     * 验证图形验证码是否正确
     */
    public Result captcha(RedisTemplate redisTemplate, String json) throws Exception{
        Result Result = null;
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(json);
        String captchaCode = jsonNode.get("captchaCode").asText();
        String captchaKey = jsonNode.get("captchaKey").asText();
        String mobile = jsonNode.get("mobile").asText();

        // 从Redis中获取验证码
        String captcha = (String) redisTemplate.opsForValue().get(captchaKey);
        // 判断验证码是否正确
        if (captcha != null && captcha.toLowerCase().equals(captchaCode.toLowerCase())) {

            //调用运营商接口发送短信
            Random r = new Random();
            String code = "";
            for (int i = 0; i < 6; i++) {
                code += r.nextInt(10);
            }
            //将短信验证码存储到Redis中，并设置有效期为5分钟
            redisTemplate.opsForValue().set(mobile, code, 5, TimeUnit.MINUTES);

            // 验证码正确
            Result = Result.success("验证码："+code);
        } else {
            // 验证码错误
            Result = Result.error("验证码错误");

        }
        return Result;
    }
}